<script lang="ts" setup>
import type { DataType } from './types';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { useRouter } from 'vue-router';

import { Page, useVbenModal } from '@vben/common-ui';

import {
  Button,
  Dropdown,
  Menu,
  MenuItem,
  message,
  Modal,
  Space,
  Tag,
} from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deletePlugin,
  getPluginConfig,
  getPlugins,
  postPlugin,
  postPluginStatus,
  putPlugin,
  putPluginConfig,
} from '#/api/admin/plugins';
import PluginSettingModalView from '#/components/ConfigFormModal';
import Icon from '#/components/Icons';
import { resetRoutes } from '#/router';

import { HooksModalView } from './components';

defineOptions({
  name: 'AdminPlugindefault',
});
const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const viewTitle = routeMeta.title.replace('管理', '');
const crow = ref();
const gridOptions: VxeGridProps<DataType> = {
  rowConfig: {
    isCurrent: true,
    isHover: true,
  },
  columns: [
    { title: '序号', type: 'seq', width: 50 },
    { field: 'title', title: '插件名称' },
    { field: 'name', title: '标识' },
    { field: 'description', title: '描述' },
    { field: 'author', title: '作者' },
    { field: 'version', title: '版本' },
    { field: 'status', title: '状态', slots: { default: 'status' } },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: '操作',
      width: 240,
    },
  ],
  height: 'auto',
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const { data } = await getPlugins({
          page: page.currentPage,
          limit: page.pageSize,
        });
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
});

const handleUpdata = async (row: DataType) => {
  const { msg } = await putPlugin(row);
  message.success(msg);
};

const [HooksModal, HooksModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: HooksModalView,
  onClosed() {
    const modalData = HooksModalApi.getData();
    if (modalData?.isUpdata) {
      GridApi.query();
      resetRoutes();
    }
  },
});

const [PluginSettingModal, PluginSettingModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: PluginSettingModalView,
  onClosed() {
    const modalData = PluginSettingModalApi.getData();
    if (modalData?.isUpdata) {
      GridApi.query();
    }
  },
});
/** 打开钩子列表窗口 */
const handleOpenHooksModel = async (row: DataType) => {
  HooksModalApi.setState({
    title: `${row.name}--钩子列表`,
  });
  HooksModalApi.setData({ row });
  HooksModalApi.open();
};

/** 打开插件设置窗口 */
const handleOpenSettingModel = async (row: DataType) => {
  PluginSettingModalApi.setState({
    title: `${row.title}--插件设置`,
  });
  crow.value = row;
  PluginSettingModalApi.setData(row);
  PluginSettingModalApi.open();
};

/** 卸载插件 */
const handleUnInstall = async (row: DataType) => {
  Modal.confirm({
    title: '系统提示',
    content: `确认要卸载${row.name}吗?`,
    async onOk() {
      const { msg } = await deletePlugin(row.id);
      message.success(msg);
      GridApi.query();
      resetRoutes();
    },
  });
};

/** 安装插件 */
const handleInstall = async (row: DataType) => {
  Modal.confirm({
    title: '系统提示',
    content: `确认要安装${row.name}吗?`,
    async onOk() {
      await postPlugin(row);
      message.success(`已安装${row.name}`);
      GridApi.query();
      resetRoutes();
    },
  });
};

async function handleManage(row: DataType) {
  const admin_url = `/plugin/${row.name.toLowerCase()}/adminindex`;
  await router.push(admin_url);
}

/** 更新状态 */
async function handleStatus(row: DataType) {
  await postPluginStatus({ id: row.id, status: row.status === 1 ? 0 : 1 });
  GridApi.query();
}

/** 提交配置处理 */
const handleConfigSubmit = async (data: Record<string, any>) => {
  try {
    const { msg } = await putPluginConfig({ id: data.id, config: data.values });
    message.success(msg);
    PluginSettingModalApi.close();
  } catch (error) {
    console.error('提交失败:', error);
  }
};

/** 获取插件配置 */
const fetchConfig = async (id: number): Promise<any> => {
  try {
    const { data } = await getPluginConfig({ id }); // API 调用返回的结果应是 Promise
    return data; // 确保返回的是 Promise 包裹的对象
  } catch (error) {
    console.error('获取配置失败:', error);
    throw error; // 如果发生错误，向上抛出以便调用者处理
  }
};
</script>

<template>
  <Page auto-content-height>
    <HooksModal />
    <PluginSettingModal
      :fetch-config="fetchConfig"
      :on-submit="handleConfigSubmit"
    />
    <Grid :table-title="`${viewTitle}列表`">
      <template #status="{ row }">
        <Tag :color="row.status === 1 ? 'success' : 'default'">
          {{ row.status === 1 ? '启用' : row.status === 0 ? '停用' : '未安装' }}
        </Tag>
      </template>
      <template #action="{ row }">
        <Space v-if="row.status === 3">
          <Button type="primary" @click="handleInstall(row)">
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:install-line" />
              </span>
            </template>
            安装
          </Button>
        </Space>
        <Space v-else>
          <Button
            :disabled="row.has_admin && row.status ? false : true"
            type="primary"
            @click="handleManage(row)"
          >
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:airplay-line" />
              </span>
            </template>
            管理
          </Button>
          <Dropdown>
            <Button type="primary">
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:settings-5-line" />
                </span>
              </template>
              设置
            </Button>
            <template #overlay>
              <Menu>
                <MenuItem v-if="!Array.isArray(row.config)">
                  <Button type="primary" @click="handleOpenSettingModel(row)">
                    <template #icon>
                      <span class="anticon">
                        <Icon icon="ri:settings-5-line" />
                      </span>
                    </template>
                    插件设置
                  </Button>
                </MenuItem>
                <MenuItem>
                  <Button type="primary" @click="handleOpenHooksModel(row)">
                    <template #icon>
                      <span class="anticon">
                        <Icon icon="ri:list-ordered" />
                      </span>
                    </template>
                    执行排序
                  </Button>
                </MenuItem>
              </Menu>
            </template>
          </Dropdown>
          <Dropdown>
            <Button type="link">
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:more-fill" />
                </span>
              </template>
            </Button>
            <template #overlay>
              <Menu>
                <MenuItem>
                  <Button type="primary" @click="handleUpdata(row)">
                    <template #icon>
                      <span class="anticon">
                        <Icon icon="ri:refresh-line" />
                      </span>
                    </template>
                    更新
                  </Button>
                </MenuItem>
                <MenuItem>
                  <Button type="primary" @click="handleStatus(row)">
                    <template #icon>
                      <span v-if="row.status === 1" class="anticon">
                        <Icon icon="ri:prohibited-line" />
                      </span>
                      <span v-else class="anticon">
                        <Icon icon="ri:prohibited-fill" />
                      </span>
                    </template>
                    {{ row.status === 1 ? '禁用' : '启用' }}
                  </Button>
                </MenuItem>
                <MenuItem>
                  <Button danger type="primary" @click="handleUnInstall(row)">
                    <template #icon>
                      <span class="anticon">
                        <Icon icon="ri:uninstall-line" />
                      </span>
                    </template>
                    卸载
                  </Button>
                </MenuItem>
              </Menu>
            </template>
          </Dropdown>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
